const util = require('util');
const execSync = require('child_process').execSync
const { spawn } = require('child_process');
const fs = require('fs')
const path = require('path')


//当前目录
const cwdPath = process.cwd();

//日志缓存
let CACHE_LOG_DATE = ""

exports.INFO = INFO = msg => {
	if(msg.indexOf("\n") === -1)
		msg+="\n";
	CACHE_LOG_DATE+= msg
	console.log(msg)
}

exports.ERROR = ERROR =  msg => {
	CACHE_LOG_DATE+= "[ERROR:]"+msg+"\n"
	console.log('\x1B[31m%s\x1B[0m', msg)
	throw msg;
}

/**
@desc 将所有info缓存的数据，写入到*.log中 clsp中请调用LOG
@param file:String  
*/
exports.OUT_LOG = OUT_LOG = file => fs.writeFileSync(file,CACHE_LOG_DATE,{encoding:"utf-8"})


/**
	@Desc 同步运行系统命令 直到命令完全结束才返回数据
	@Param cmd:String 命令字符串 
	@Param printFlag:String 设置自动打印输出 默认：打印
*/
exports.SHELL = SHELL = (cmd,isPrint=true)=>{

	//因为exec命令 会对 ' 符号进行一次转换
	if(cmd.trim().indexOf("opc") == 0 && cmd.indexOf(`'`) > -1)
		throw `please use " instead of ',example opc '(1 2)' -> opc "(1 2)"`

	isPrint &&	INFO(`> ${cmd}`)

	try{

		const result = execSync(cmd).toString();

		isPrint && INFO(`~ ${result}`)

		return result.replace(/[\r\n]/g,"");

	}catch(e){
		throw `调用失败:${e.stdout.toString()}`
	}


}


/**
	@Desc 运行系统命令 异步返回信息
	@Param cmd:String 命令字符串 
	@Param args:[String] 参数数组
	@Param printFlag:String 设置自动打印输出 默认：打印
*/
exports.SHELL_ASYNC = SHELL_ASYNC = async (cmd,args,isPrint=true) => {

	const print = msg => isPrint &&	INFO(msg.toString())

	print(`> ${cmd} ${args}`)

	const ls = spawn(cmd,args);

	return new Promise((resolve,reject)=>{

		let dataSum = "";

		ls.stdout.on('data', d => {
			print(d)
			dataSum+=d;
		});

		ls.stderr.on('data', print);

		ls.on('close', (code) => {
		  resolve(ls)
		});

	})

}

exports.XCH_RATE = XCH_RATE = 1000000000000;

//chia 1xch等于XCH_RATE mojo  实际都以mojo运行
exports.XCH_TO_MOJO = XCH_TO_MOJO = num => num * XCH_RATE;

//将mojo兑换成xch
exports.MOJO_TO_XCH = MOJO_TO_XCH = (numStr) => {
	const num = numStr/XCH_RATE;
	const m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
	return num.toFixed(Math.max(0, (m[1] || '').length - m[2]));
}


exports.RANDOM_STRING = RANDOM_STRING = e => {    
    e = e || 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
    a = t.length,
    n = "";
    for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n
}

//创建临时文件
exports.CREATE_TEMP_FILE = CREATE_TEMP_FILE = (fileName,content) => {
	const t = fileName.split(".")
	const realName = `${RANDOM_STRING(4)}_${t[0]}_runtime.${t[1]}`
	const tempFile = path.join(__DIRNAME,realName)
	TEMP_FILES.push(tempFile)
	fs.writeFileSync(tempFile,content,{encoding:"utf-8"})
	return {realName,tempFile};
}

exports.isInteger = isInteger = obj => typeof obj === 'number' && obj%1 === 0
	
exports.isString = isString = obj => typeof obj === 'string'

exports.convertToStdHex = convertToStdHex = hexStr => hexStr.indexOf("0x") === 0 ? hexStr.substring(2,hexStr.length) : hexStr;





